/**
 * Wihidum - Efficient Broker Hierarchy for Publish Subscribe Middleware
 *
 * License      :   Apache License 2.0
 * Home Page    :   http://code.google.com/p/wihidum/
 * Mailing List :   wihidum@googlegroups.com
 */

package lk.mrt.cse.wihidum.processor;

import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.om.*;
import org.apache.log4j.Logger;
import lk.mrt.cse.wihidum.util.WSEventingConstants;
import lk.mrt.cse.wihidum.storage.Broker;
import lk.mrt.cse.wihidum.storage.BrokerList;
import lk.mrt.cse.wihidum.trace.TotalMessageTrace;

import javax.xml.namespace.QName;

public class SetMessageTraceProcessor implements Processor
{
    private static final Logger logger = Logger.getLogger(SetMessageTraceProcessor.class);

    public SOAPEnvelope processMessage(SOAPEnvelope requestEnvelope)
    {
        try {
            OMElement traceElement = requestEnvelope.getBody()
                    .getFirstChildWithName(new QName(WSEventingConstants.WIHIDUM_NAMESPACE, "DistributionTrace"));

            String trace=traceElement.getText();
            TotalMessageTrace.addMessageTrace(trace);
            return this.createSetTraceResponseElement();
        }
        catch (NullPointerException ex)
        {
            logger.error("Error in processing received set message trace message", ex);
            return null;
        }
        catch (OMException ex)
        {
            logger.error("Error in processing received insert broker message", ex);
            return null;
        }
    }

    private SOAPEnvelope createSetTraceResponseElement()
    {
        SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory();
        SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope();
        
        //declare the used namespaces in the SOAP Envelope
        OMNamespace wseventingNS = soapFactory.createOMNamespace(WSEventingConstants.EVENTING_NAMESPACE, WSEventingConstants.EVENTING_PREFIX);
        soapEnvelope.declareNamespace(wseventingNS);
        OMNamespace wsaNS = soapFactory.createOMNamespace(WSEventingConstants.ADDRESSING_NAMESPACE, WSEventingConstants.ADDRESSING_PREFIX);
        soapEnvelope.declareNamespace(wsaNS);
        OMNamespace wihidumNS = soapFactory.createOMNamespace(WSEventingConstants.WIHIDUM_NAMESPACE, WSEventingConstants.WHIDUM_NAMESPACE_PREFIX);
        soapEnvelope.declareNamespace(wihidumNS);

        OMFactory factory = OMAbstractFactory.getOMFactory();

        OMElement responceElement = factory.createOMElement("SetTraceRespose", wihidumNS);
        responceElement.setText("Message trace received successfully");

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addChild(responceElement);

        return soapEnvelope;
    }
}

